from django.db import models
from django.contrib.auth.models import User

class Tenant(models.Model):
    name = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class FormTemplate(models.Model):
    FIELD_TYPES = (
        ('text', '文本框'),
        ('number', '数字框'),
        ('radio', '单选框'),
        ('checkbox', '复选框'),
        ('select', '下拉菜单'),
        ('image', '图片上传'),
    )

    tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)

    def delete(self, *args, **kwargs):
        # 删除所有相关的提交记录
        self.formsubmission_set.all().delete()
        # 删除所有字段组（会级联删除字段）
        self.sections.all().delete()
        # 删除表单本身
        super().delete(*args, **kwargs)

    def __str__(self):
        return f"{self.tenant.name} - {self.title}"

class FormSection(models.Model):
    template = models.ForeignKey(FormTemplate, on_delete=models.CASCADE, related_name='sections')
    title = models.CharField(max_length=100)
    order = models.IntegerField()

    class Meta:
        ordering = ['order']

    def __str__(self):
        return f"{self.template.title} - {self.title}"

    def delete(self, *args, **kwargs):
        # 删除所有相关字段
        self.formfield_set.all().delete()
        # 删除字段组本身
        super().delete(*args, **kwargs)

class FormField(models.Model):
    template = models.ForeignKey(FormTemplate, on_delete=models.CASCADE)
    section = models.ForeignKey(FormSection, on_delete=models.CASCADE)
    label = models.CharField(max_length=100)
    field_type = models.CharField(max_length=20)
    required = models.BooleanField(default=False)
    options = models.TextField(null=True, blank=True)
    order = models.IntegerField()

    class Meta:
        ordering = ['section__order', 'order']

class FormSubmission(models.Model):
    template = models.ForeignKey(FormTemplate, on_delete=models.CASCADE)
    submitted_by = models.ForeignKey(User, on_delete=models.CASCADE)
    submitted_at = models.DateTimeField(auto_now_add=True)
    data = models.JSONField()  # 存储表单数据 